import pymysql


class cf():
    conn=None
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn=pymysql.Connect(host="192.168.88.128", port=3306,user="root" , passwd="123456",
                       database="test_db", charset="utf8")
        return cls.conn
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn=None

    @classmethod
    def select_many(cls,self):
        conn=cls.__get_conn()
        cursor=None
        c=0
        try:
            cursor=conn.cursor()
            cursor.execute(self)
            c=cursor.fetchmany(10)
        except Exception as k:
            print("捕获异常为k",k)
            raise k
        finally:
            if cursor is not None:
                cursor.close()
                cls.__close_conn()
            return c

    @classmethod
    def xz_(cls,self):
        conn=cls.__get_conn()
        cursor=None
        try:
            cursor=conn.cursor()
            cursor.execute(self)
            cursor.fetchone()
            conn.commit()
        except Exception as d:
            print("发生了插入错误",d)
            if conn!=0:
                conn.rollback()
            raise d
        finally:
            if cursor is not None:
                cursor.close()
                conn.close()

if __name__ == '__main__':
    print(cf.select_many("select * from t_book"))
    cf.xz_("insert into t_book (id ,title,pub_date) values(21,'20','1986-15-20')")
